﻿using NxERP.Bll;

using NxStoreManage;

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LengthAiCalculate
{
    public partial class AICalculateFrm : BaseForm
    {
        private readonly string BaseDir;

        private readonly string SystemBit;

        private readonly string ZipFile;

        private const string scSql = "SELECT lg 长度,numBack 支数,num 剩余支数,id 序号,CONVERT(FLOAT,cutHeadRate*100.00) 切头率 FROM [PM.AiSc]";

        private const string jhSql = "SELECT lg 长度,CASE WHEN numBack IS NULL THEN 0 ELSE numBack END 订单支数,num 欠支数,id 序号,oBz 备注 FROM [PM.AiJh]";

        private const string resultSq = "SELECT id 序号,cutGroup 锯切组合,mLength 原料长度,num 消耗支数,twoCutNum 分拆支数,CASE WHEN isAbandon > 0 THEN '有' ELSE '无' END 废钢,CASE isUserAdd WHEN 1 THEN '是' ELSE '否' END 人工添加,CASE resultType WHEN 2 THEN '按料编排' WHEN 1 THEN '理想编排' ELSE '未知方式' END 匹配方式 FROM [PM.AiResult]";

        private DataTable dt2 = new DataTable();

        public static string isSave = "(0,1)";

        public static string isEnd = "(0,1)";
        public static int planNameNum = 3;

        public AICalculateFrm()
        {
            InitializeComponent();
            timer1.Enabled = false;
            timer1.Interval = 10;
            toolStripStatusLabel1.Text = "  软件版本:" + SysInit.GetVersion();
            comboBox4.SelectedIndex = 0;
            if (Environment.Is64BitOperatingSystem)
            {
                SystemBit = "64";
            }
            else
            {
                SystemBit = "32";
            }
            BaseDir = StartupPath + $@"\cutting{SystemBit}\";
            ZipFile = StartupPath + $@"\cutting{SystemBit}.zip";
            Text += "(" + SystemBit + "位)";
            toolStripStatusLabel3.Text = LengthAiCalculate.Properties.Settings.Default.logDir;
        }

        private DataTable scdt;

        private DataTable jhdt;

        private void Button1_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string path = openFileDialog1.FileName;
                if (NopiHelp.CheckSheetName(path, "原料") && NopiHelp.CheckSheetName(path, "订单"))
                {
                    comboBox3.SelectedIndexChanged -= ComboBox3_SelectedIndexChanged;
                    scdt = NopiHelp.ExcelToDataTable(path, "原料", true);
                    jhdt = NopiHelp.ExcelToDataTable(path, "订单", true);

                    if (scdt.Columns.Contains("长度") == false)
                    {
                        MessageBox.Show("原料表缺少长度列！", "错误提示!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    if (scdt.Columns.Contains("支数") == false)
                    {
                        MessageBox.Show("原料表支数列！", "错误提示!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    if (jhdt.Columns.Contains("长度") == false)
                    {
                        MessageBox.Show("订单表缺少长度列！", "错误提示!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    if (jhdt.Columns.Contains("支数") == false)
                    {
                        MessageBox.Show("订单表缺少支数列！", "错误提示!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    if (double.TryParse(jhdt.Rows[0]["长度"].ToString(), out _) == false)
                    {
                        textBox5.Text = jhdt.Rows[0]["长度"].ToString();
                        textBox6.Text = jhdt.Rows[0]["支数"].ToString();
                        jhdt.Rows.RemoveAt(0);
                    }
                    else
                    {
                        textBox5.Text = "";
                        textBox6.Text = "";
                    }
                    if (double.TryParse(scdt.Rows[0]["长度"].ToString(), out _) == false)
                    {
                        comboBox3.Text = scdt.Rows[0]["长度"].ToString();
                        textBox15.Text = scdt.Rows[0]["支数"].ToString();
                        scdt.Rows.RemoveAt(0);
                    }
                    else
                    {
                        comboBox3.Text = "";
                        textBox15.Text = "";
                    }
                    dataGridView1.DataSource = scdt;

                    //dataGridView1.Columns["序号"].Visible = false;
                    //dataGridView1.Columns[1].HeaderText = "排产支数";
                    dataGridView2.DataSource = jhdt;

                    //dataGridView2.Columns["序号"].Visible = false;
                    //dataGridView2.Columns[1].HeaderText = "订单支数";
                    button2.Enabled = true;
                    button18.Enabled = true;
                }
            }
        }

        private void Button2_Click(object sender, EventArgs e)
        {
            if (jhdt == null && scdt == null)
            {
                ShowError("请先打开计划文件！");
                return;
            }
            if (textBox5.Text.Trim().Length == 0 || textBox6.Text.Trim().Length == 0 || textBox15.Text.Trim().Length == 0 || comboBox3.Text.Length == 0)
            {
                ShowError("产线、控制号、规格、钢级必须填");
                return;
            }
            string mID = Guid.NewGuid().ToString("N");
            List<string> sqlList = new List<string>
            {
                $@"INSERT INTO [PM.Ai]
                (
                    mID,
                    planName,
                    lineName,
                    planSize,
                    planSteel,userCode,isSave,isEnd
                )
                VALUES
                ('{mID}',
                    '{textBox15.Text}',
                    '{comboBox3.Text}',
                    '{textBox5.Text}',
                    '{textBox6.Text}','{LoginUser.LoginUserCode}',0,0
                    )"
            };
            foreach (DataRow scRow in scdt.Rows)
            {
                string lg = scRow["长度"].ToString();
                string num = scRow["支数"].ToString();
                double cutHeadRate = 0;
                if (scdt.Columns.Contains("切头率"))
                {
                    double.TryParse(scRow["切头率"].ToString(), out cutHeadRate);
                }
                cutHeadRate /= 100.00;
                if (double.TryParse(lg, out var _lg) && int.TryParse(num, out var _num) && _lg > 0 && _num > 0)
                {
                    sqlList.Add($@"IF  EXISTS (SELECT * FROM [PM.AiSc] WHERE mID='{mID}' AND lg={lg}) UPDATE [PM.AiSc] SET num=num+{num} WHERE mID='{mID}' AND lg={lg} ELSE INSERT [PM.AiSc]
                            (
                                lg,
                                num,
                                isdel,
                                mID,
                                numBack,
                                realNum,cutHeadRate
                            )
                            VALUES
                            (   {lg},
                                {num},
                                0,
                                '{mID}',{num},0,{cutHeadRate}
                                )");
                }
            }
            foreach (DataRow jhRow in jhdt.Rows)
            {
                {
                    string lg = jhRow["长度"].ToString();
                    string num = jhRow["支数"].ToString();
                    if (double.TryParse(lg, out var _lg) && int.TryParse(num, out var _num) && _lg > 0 && _num > 0)
                    {
                        sqlList.Add($@"IF  EXISTS (SELECT * FROM [PM.AiJh] WHERE mID='{mID}' AND lg={lg}) UPDATE [PM.AiJh] SET num=num+{num} WHERE mId='{mID}' AND lg={lg} ELSE INSERT INTO
                                [PM.AiJh]
                                (
                                    lg,
                                    num,
                                    isdel,
                                    cutGroupNum,
                                    mNum,
                                    mId,numBack,realNum,cutNum
                                )
                                VALUES
                                (  {lg},
                                    {num},
                                    0,
                                    NULL,
                                    NULL,
                                    '{mID}',{num},0,0
                                    )");
                    }
                }
            }
            if (nxsqlHelper.ExcuteSql(sqlList) > 0)
            {
                BindCombox2();
                Reload();
                comboBox3.SelectedIndexChanged += ComboBox3_SelectedIndexChanged;
                button2.Enabled = false;
                button18.Enabled = false;
                ShowMsg("数据导入成功！");
            }
        }

        private void SumLength()
        {
            decimal.TryParse(textBox17.Text, out var l1);
            decimal.TryParse(textBox16.Text, out var l2);
            decimal.TryParse(textBox9.Text, out var l3);
            int.TryParse(textBox10.Text, out var num1);
            int.TryParse(textBox4.Text, out var num2);
            int.TryParse(textBox3.Text, out var num3);
            l1 *= 1.0m;
            l2 *= 1.0m;
            l3 *= 1.0m;
            decimal l = Math.Round(l1 * num1 + l2 * num2 + l3 * num3, 1);
            textBox7.Text = l.ToString();
            button16.Enabled = false;
            decimal.TryParse(textBox7.Text, out var _lg);
            int.TryParse(textBox8.Text, out var _num);
            foreach (DataGridViewRow item in dataGridView1.Rows)
            {
                decimal.TryParse(item.Cells["sclg"].Value.ToString(), out var lg);
                int.TryParse(item.Cells["scnumback"].Value.ToString(), out var scnumback);
                if (lg == _lg)
                {
                    button16.Enabled = true;
                    break;
                }
            }
            if (_num == 0)
            {
                button16.Enabled = false;
            }
        }

        private void ButtonEnable(bool enable, Button btn)
        {
            button1.Enabled = enable;
            button2.Enabled = enable;
            button3.Enabled = enable;
            button4.Enabled = enable;
            if (btn.Name == "button4")
            {
                if (enable)
                {
                    button4.Text = "计算";
                }
                else
                {
                    button4.Text = "计算中";
                }
            }
            button6.Enabled = enable;
            button7.Enabled = enable;
            button5.Enabled = enable;
            button17.Enabled = enable;
            if (btn.Name == "button17")
            {
                if (enable)
                {
                    button17.Text = "初始化";
                }
                else
                {
                    button17.Text = "初始化中";
                }
            }
        }

        private void Button4_Click(object sender, EventArgs e)
        {
            string mid = null;
            if (comboBox2.SelectedValue != null)
            {
                mid = comboBox2.SelectedValue.ToString();
            }
            if (string.IsNullOrEmpty(mid))
            {
                ShowError("请选择要计算的计划！");
                return;
            }
            Stopwatch sw = new Stopwatch();
            sw.Start();
            ButtonEnable(false, button4);
            int priority = comboBox1.SelectedIndex;
            progressBar1.Maximum = 3;
            progressBar1.Value = 0;
            Task task = Task.Factory.StartNew(() =>
            {
                double.TryParse(textBox1.Text, out var cutLength);
                if (cutLength < 0)
                {
                    cutLength = 1;
                }
                Ai ai = new Ai(nxsqlHelper, mid, cutLength, false);
                ai.BaseOp();
                Invoke(new Action(() =>
                {
                    progressBar1.Value += 1;
                }));
                if (priority == 0)
                {
                    ai.C2();
                }
                else
                {
                    ai.C1();
                }
                Invoke(new Action(() =>
                {
                    progressBar1.Value += 1;
                }));
                if (checkBox1.Checked)
                {
                    ai.C3();
                }
                Invoke(new Action(() =>
                {
                    progressBar1.Value += 1;
                }));
            });
            task.ContinueWith(t =>
            {
                ButtonEnable(true, button4);
                Sum(mid);
                Reload();
                sw.Stop();
                TimeSpan ts = sw.Elapsed;
                MessageBox.Show("计算成功，耗时:" + ts.Hours.ToString() + "小时" + ts.Minutes.ToString() + "分钟" + ts.Seconds + "秒" + ts.Milliseconds + "毫秒", "提示！");
            }, TaskScheduler.FromCurrentSynchronizationContext());
        }

        private void AICalculateFrmcs_Load(object sender, EventArgs e)
        {
            if (DateTime.Now.Day % 5 == 0)
            {
                nxsqlHelper.ExcuteSql($@"UPDATE [PM.Ai]
            SET isEnd = 1,
                isSave = 1
            WHERE planName IN
                  (
                      SELECT KZH
                      FROM {SysInit.GetSBServer()}SB_StoreOut
                      WHERE T = 1
                  )
                  AND isEnd = 0;
            UPDATE [PM.PlanMain]
            SET [state] = 2
            WHERE planName IN
                  (
                      SELECT KZH
                      FROM {SysInit.GetSBServer()}SB_StoreOut
                      WHERE T = 1
                  )
                  AND [state] <> 2;");
            }
            comboBox1.SelectedIndex = 0;
            BindCombox2();
            SetDataGridDefault(dataGridView1, rowHeadersVisible: false); ;
            SetDataGridDefault(dataGridView2, rowHeadersVisible: false);
            SetDataGridDefault(dataGridView3, rowHeadersVisible: false);
            DataTable lineDt = sB_sqlHelper.GetDataTableFromSql("SELECT lineCode,lineName FROM SB_p_Line");
            BindComboBox(comboBox3, lineDt);
            timer1.Enabled = true;
        }

        private void BindCombox2()
        {
            if (comboBox3.SelectedItem != null)
            {
                if (comboBox5.SelectedItem != null)
                {
                    dt2 = nxsqlHelper.GetDataTableFromSql($@"SELECT [mID], planSize + '(' + planSteel + ')' + '(' + [planName] + ')' planstring FROM [PM.Ai] WHERE isSave IN {isSave} AND isEnd IN {isEnd} AND lineName='{comboBox3.Text}' AND planName='{comboBox5.SelectedValue}'  ORDER BY orderBy ASC");
                }
                else
                {
                    dt2 = nxsqlHelper.GetDataTableFromSql($@"SELECT [mID], planSize + '(' + planSteel + ')' + '(' + [planName] + ')' planstring FROM [PM.Ai] WHERE 1=0 ORDER BY orderBy ASC");
                }
            }
            else
            {
                dt2 = nxsqlHelper.GetDataTableFromSql($@"SELECT [mID], planSize + '(' + planSteel + ')' + '(' + [planName] + ')' planstring FROM [PM.Ai] WHERE 1=0 ORDER BY orderBy ASC");
            }
            BindComboBox(comboBox2, dt2);
        }

        private DataTable dt5 = new DataTable();

        private void BindCombox5()
        {
            if (comboBox3.SelectedItem != null)
            {
                dt5 = nxsqlHelper.GetDataTableFromSql($@"SELECT DISTINCT TOP ({planNameNum}) planName,
                   CASE
                       WHEN CHARINDEX('*', planSize) > 1 THEN
                           SUBSTRING(planSize, 1, CHARINDEX('*', planSize) - 1) + '(' + planName + ')'
                       ELSE
                           planSize + +'(' + planName + ')'
                   END planSize
                   FROM [PM.Ai] WHERE isSave IN {isSave} AND isEnd IN {isEnd} AND lineName='{comboBox3.Text}' ORDER BY planName DESC");
                BindComboBox(comboBox5, dt5);
                dt5.DefaultView.RowFilter = $"planSize LIKE '%{textBox18.Text.Trim()}%'";
            }
        }

        private void ComboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            Reload();
        }

        public void Reload()
        {
            button2.Enabled = false;
            button18.Enabled = false;
            button8.Enabled = true;
            if (comboBox2.SelectedValue != null)
            {
                scdt = nxsqlHelper.GetDataTableFromSql($"{scSql} WHERE mId='{comboBox2.SelectedValue}'");
                jhdt = nxsqlHelper.GetDataTableFromSql($"{jhSql} WHERE mId='{comboBox2.SelectedValue}' ORDER BY lg DESC");
                dataGridView1.DataSource = scdt;
                dataGridView2.DataSource = jhdt;
                button4.Enabled = true;
                groupBox1.Enabled = true;
                dataGridView3.DataSource = nxsqlHelper.GetDataTableFromSql($@"{resultSq} WHERE mID='{comboBox2.SelectedValue}' ORDER BY id ASC");
                if (dataGridView3.Rows.Count > 0)
                {
                    button8.Enabled = true;
                }
                textBox20.Text = comboBox2.SelectedValue.ToString();
            }
            else
            {
                dataGridView1.DataSource = nxsqlHelper.GetDataTableFromSql($"{scSql} WHERE mId='N'"); ;
                dataGridView2.DataSource = nxsqlHelper.GetDataTableFromSql($"{jhSql} WHERE mId='N'  ORDER BY lg DESC"); ;
                dataGridView3.DataSource = nxsqlHelper.GetDataTableFromSql($@"{resultSq} WHERE mID='N' ORDER BY mLength ASC");
                button4.Enabled = false;
                groupBox1.Enabled = false;
                Sum("N"); textBox20.Text = "";
            }
            if (dataGridView1.Columns.Contains("序号"))
            {
                dataGridView1.Columns["序号"].Visible = false;
            }
            if (dataGridView2.Columns.Contains("序号"))
            {
                dataGridView2.Columns["序号"].Visible = false;
            }
            for (int i = 0; i < dataGridView1.Columns.Count; i++)
            {
                dataGridView1.Columns[i].Width = 80;
            }
            for (int i = 0; i < dataGridView2.Columns.Count; i++)
            {
                dataGridView2.Columns[i].Width = 80;
            }
            button16.Enabled = true;
            if (comboBox2.SelectedValue != null)
            {
                string mid = comboBox2.SelectedValue.ToString();
                GetResult(mid);
                scdt = nxsqlHelper.GetDataTableFromSql($"{scSql} WHERE mId='{comboBox2.SelectedValue}'");
                jhdt = nxsqlHelper.GetDataTableFromSql($"{jhSql} WHERE mId='{comboBox2.SelectedValue}' ORDER BY lg DESC");
                dataGridView1.DataSource = scdt;
                dataGridView2.DataSource = jhdt;
                Sum(mid);
            }
        }

        private void Button5_Click(object sender, EventArgs e)
        {
            if (comboBox2.SelectedValue != null)
            {
                string mid = comboBox2.SelectedValue.ToString();
                if (nxsqlHelper.ExcuteSql($@"DELETE [PM.Ai] WHERE mID='{mid}'; DELETE [PM.AiSc] WHERE mID='{mid}'; DELETE [PM.AiJh] WHERE mId='{mid}'; DELETE [PM.AiResult] WHERE mID='{mid}'") > 0)
                {
                    BindCombox2();
                    Reload();
                    ShowMsg("删除成功");
                }
            }
            else
            {
                ShowError("先选择要删除的计划！");
            }
        }

        private void Button3_Click(object sender, EventArgs e)
        {
            if (comboBox2.SelectedValue == null)
            {
                ShowError("选择要添加的计划！");
                return;
            }
            int.TryParse(textBox12.Text, out var num);
            double.TryParse(textBox11.Text, out var lg);
            double.TryParse(textBox2.Text, out var cutHeadRate);
            if (cutHeadRate < 0 || cutHeadRate > 50)
            {
                ShowError("切头率不合理，请检查！");
                return;
            }
            if (lg < 24 || lg > 59.5)
            {
                ShowError("原料长度必须在24-59.5之间");
                return;
            }
            var ys = lg % 0.5;
            //if (ys > 0)
            //{
            //    ShowError("只能处理0.5倍长度!");
            //    return;
            //}
            //if (num < 0)
            //{
            //    ShowError("原料支数必须大于0");
            //    return;
            //}
            cutHeadRate /= 100.00;
            string mid = comboBox2.SelectedValue.ToString();
            List<string> sqlList = new List<string>();

            //sqlList.Add($"DELETE [PM.AiResult] WHERE mID='{mid}'");
            sqlList.Add($"IF EXISTS (SELECT * FROM [PM.AiSc] WHERE mId = '{mid}' AND lg = {lg}) UPDATE [PM.AiSc] SET num = num + {num}, numBack = numBack + {num},cutHeadRate={cutHeadRate} WHERE mId = '{mid}' AND lg = {lg} ELSE INSERT INTO [PM.AiSc] (lg,num,isdel,mID,numBack,realNum,cutHeadRate) VALUES ({lg},{num},0,'{mid}',{num},0,{cutHeadRate})");
            sqlList.Add($@"UPDATE [PM.AiSc] SET num=numBack WHERE mID='{mid}'");
            if (nxsqlHelper.ExcuteSql(sqlList) > 0)
            {
                Reload();
                ShowMsg("添加成功！");
            }
        }

        private void Button6_Click(object sender, EventArgs e)
        {
            if (comboBox2.SelectedValue == null)
            {
                ShowError("选择要添加的计划！");
                return;
            }

            int.TryParse(textBox14.Text, out var num);
            double.TryParse(textBox13.Text, out var lg);
            if (lg < 6 || lg > 20)
            {
                ShowError("成品长度必须在6-20之间");
                return;
            }
            //var ys = lg % 0.5;
            //if (ys > 0)
            //{
            //    ShowError("只能处理0.5倍定尺!");
            //    return;
            //}
            //if (num < 0)
            //{
            //    ShowError("成品支数必须大于0");
            //    return;
            //}
            string mid = comboBox2.SelectedValue.ToString();
            List<string> sqlList = new List<string>();

            //sqlList.Add($"DELETE [PM.AiResult] WHERE mID='{mid}'");
            sqlList.Add($"DELETE [PM.AiJh] WHERE mId='{mid}' AND numBack IS NULL");
            sqlList.Add($@"IF EXISTS (SELECT * FROM [PM.AiJh] WHERE mId = '{mid}' AND lg = {lg}) UPDATE [PM.AiJh] SET num = num + ({num}), numBack = numBack + ({num}) WHERE mId = '{mid}' AND lg = {lg} ELSE INSERT INTO [PM.AiJh] (lg,num,isdel,cutGroupNum,mNum,mId,numBack,realNum,cutNum) VALUES ({lg},{num},0,NULL,NULL,'{mid}',{num},0,0)");
            sqlList.Add($"UPDATE [PM.AiSc] SET num=numBack WHERE mID='{mid}'");
            if (nxsqlHelper.ExcuteSql(sqlList) > 0)
            {
                Reload();
                ShowMsg("添加成功！");
            }
        }

        private void Button7_Click(object sender, EventArgs e)
        {
            if (textBox5.Text.Trim().Length == 0 || textBox6.Text.Trim().Length == 0 || textBox15.Text.Trim().Length == 0 || comboBox3.Text.Length == 0)
            {
                ShowError("产线、控制号、规格、钢级必须填");
                return;
            }
            string mID = Guid.NewGuid().ToString("N");
            if (nxsqlHelper.ExcuteSql($@"INSERT INTO [PM.Ai]
                (
                    mID,
                    planName,
                    lineName,
                    planSize,
                    planSteel,
                    userCode,isSave,isEnd
                )
                VALUES
                (   '{mID}',
                    '{textBox15.Text.Trim()}',
                    '{comboBox3.Text.Trim()}',
                    '{textBox5.Text.Trim()}',
                    '{textBox6.Text.Trim()}',
                    '{LoginUser.LoginUserCode}',0,0
                    )") > 0)
            {
                BindCombox2();
                ShowMsg("创建成功！");
            }
        }

        private void Sum(string mid)
        {
            if (mid.ToUpper() == "N")
            {
                label4.Text = "0.00%";
                label6.Text = "0.00%";
                //label12.Text = "0.00%";
                label8.Text = "0种";
                label38.Text = "0.00000%";
                return;
            }
            var result = Ai.Sum(nxsqlHelper, mid);
            label4.Text = result.JhPlanPercent.ToString("0.00") + "%";
            label6.Text = result.JhNoPlanPercent.ToString("0.00") + "%";
            //label12.Text = result.RealPercent.ToString("0.00") + "%";
            label8.Text = dataGridView3.Rows.Count.ToString() + "种";
            label38.Text = result.NoUsePercent.ToString("0.00000") + "%";
        }

        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DataGridView dg = (DataGridView)GetOwnerContextMenuStrip(sender);
            string id = "0";
            if (dg.SelectedRows.Count > 0)
            {
                if (comboBox2.SelectedValue == null)
                {
                    ShowError("临时数据还未导入，无法删除");
                    return;
                }
                string mid = comboBox2.SelectedValue.ToString();
                int i;
                if (dg.Name == "dataGridView1")
                {
                    id = dg.SelectedRows[0].Cells["scid"].Value.ToString();
                    if (id == "")
                    {
                        ShowError("临时数据还未导入，无法删除");
                        return;
                    }
                    i = nxsqlHelper.ExcuteSql($"DELETE [PM.AiSc] WHERE id={id};UPDATE [PM.AiSc] SET num=numBack WHERE mID='{mid}';UPDATE [PM.AiJh] SET num=numBack WHERE mID='{mid}'");
                }
                else
                {
                    id = dg.SelectedRows[0].Cells["jhid"].Value.ToString();
                    if (id == "")
                    {
                        ShowError("临时数据还未导入，无法删除");
                        return;
                    }
                    i = nxsqlHelper.ExcuteSql($"DELETE [PM.AiJh] WHERE id={id};UPDATE [PM.AiSc] SET num=numBack WHERE mID='{mid}';UPDATE [PM.AiJh] SET num=numBack WHERE mID='{mid}'");
                }
                if (i > 0)
                {
                    ShowMsg("移除成功！");
                }
                Reload();
            }
            else
            {
                ShowError("选择要移除的行！");
            }
        }

        private void Button8_Click(object sender, EventArgs e)
        {
            if (comboBox2.SelectedValue != null && dataGridView3.Rows.Count > 0)
            {
                DataTable dt = nxsqlHelper.GetDataTableFromSql($"SELECT mLength FROM [PM.AiResult] WHERE mID='{comboBox2.SelectedValue}'");
                List<string> up = new List<string>();
                up.Add($"UPDATE [PM.Ai] SET priorityType={comboBox2.SelectedIndex},isSave=1 WHERE mID='{comboBox2.SelectedValue}'");
                foreach (DataRow item in dt.Rows)
                {
                    string lg = item["mLength"].ToString();
                    string cutHeadRate = nxsqlHelper.GetColumnValue("[PM.AiSc]", "cutHeadRate", $"mID='{comboBox2.SelectedValue}'");
                    if (cutHeadRate != "")
                    {
                        up.Add($"UPDATE [PM.AiResult] SET cutHeadRate={cutHeadRate} WHERE mLength={lg} AND mID='{comboBox2.SelectedValue}'");
                    }
                }
                if (up.Any())
                {
                    nxsqlHelper.ExcuteSql(up);
                }
                BindCombox2();
                Reload();
                ShowMsg("保存成功！");
            }
            else
            {
                ShowError("没有结果要保存！");
            }
        }

        private Ai ai;

        private void Button10_Click(object sender, EventArgs e)
        {
            if (ai != null)
            {
                ai.C1();
                Reload();
                ShowMsg("计算完成！");
            }
            else
            {
                ShowError("请先初始化和基本计算后再操作这一步！");
            }
        }

        private void Button9_Click(object sender, EventArgs e)
        {
            if (ai != null)
            {
                ai.BaseOp();
                Reload();
                ShowMsg("计算完成！");
            }
            else
            {
                ShowError("请先进行初始化！");
            }
        }

        private void Button11_Click(object sender, EventArgs e)
        {
            if (ai != null)
            {
                ai.C2();
                Reload();
                ShowMsg("计算完成！");
            }
            else
            {
                ShowError("请先初始化和基本计算后再操作这一步！");
            }
        }

        private void Button13_Click(object sender, EventArgs e)
        {
            if (comboBox2.SelectedValue == null)
            {
                ShowMsg("没有选择计划！");
                return;
            }
            ai = new Ai(nxsqlHelper, comboBox2.SelectedValue.ToString(), int.Parse(textBox1.Text), false);
            Reload();
            ShowMsg("初始化完成！");
        }

        private void Button12_Click(object sender, EventArgs e)
        {
            if (ai != null)
            {
                ai.C3();
                Reload();
                ShowMsg("计算完成！");
            }
            else
            {
                ShowError("请先初始化和基本计算后再操作这一步！");
            }
        }

        public ManufactureFrm manufactureFrm;

        private void 进入生产ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (manufactureFrm == null || manufactureFrm.Disposing)
            {
                manufactureFrm = new ManufactureFrm();
            }
            manufactureFrm.aICalculateFrm = this;
            SetShowFormDefault(manufactureFrm);
            manufactureFrm.RefreshData(true);
            manufactureFrm.Show();
            Hide();
        }

        private void ComboBox3_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindCombox5();
        }

        private void Button15_Click(object sender, EventArgs e)
        {
            string fileSource = StartupPath + @"\计划模板.xlsx"; //源文件
            using (SaveFileDialog saveFileDialog1 = new SaveFileDialog())
            {
                saveFileDialog1.Title = "另存为";
                saveFileDialog1.FileName = "计划模板.xlsx"; //设置默认另存为的名字，可选
                saveFileDialog1.Filter = "Excel 文件(*.xlsx)|*.xls";
                saveFileDialog1.AddExtension = true;
                saveFileDialog1.RestoreDirectory = true;
                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    System.IO.File.Copy(fileSource, saveFileDialog1.FileName, true);
                    ShowMsg("保存成功！");
                }
            }
        }

        private void TextBox17_TextChanged(object sender, EventArgs e)
        {
            SumLength();
        }

        private void TextBox9_TextChanged(object sender, EventArgs e)
        {
            SumLength();
        }

        private void TextBox4_TextChanged(object sender, EventArgs e)
        {
            SumLength();
        }

        private void TextBox3_TextChanged(object sender, EventArgs e)
        {
            SumLength();
        }

        private void TextBox16_TextChanged(object sender, EventArgs e)
        {
            SumLength();
        }

        private void TextBox10_TextChanged(object sender, EventArgs e)
        {
            SumLength();
        }

        private void DataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            if (dataGridView1.Rows.Count == 0)
            {
                button16.Enabled = false;
            }
            else
            {
                SumLength();
            }
        }

        private void Button16_Click(object sender, EventArgs e)
        {
            if (comboBox2.SelectedValue == null)
            {
                ShowMsg("没有选择计划！");
                return;
            }
            string mid = comboBox2.SelectedValue.ToString();
            List<string> sql = new List<string>();
            decimal.TryParse(textBox17.Text, out var l1);
            decimal.TryParse(textBox16.Text, out var l2);
            decimal.TryParse(textBox9.Text, out var l3);
            int.TryParse(textBox10.Text, out var num1);
            int.TryParse(textBox4.Text, out var num2);
            int.TryParse(textBox3.Text, out var num3);
            decimal.TryParse(textBox7.Text, out var _lg);
            int.TryParse(textBox8.Text, out var _num);
            if (l1 > 0 && num1 > 0)
            {
                sql.Add($@"IF EXISTS (SELECT * FROM [PM.AiJh] WHERE mId='{mid}' AND lg={l1})UPDATE [PM.AiJh] SET num=num-({num1 * _num}) WHERE mId='{mid}' AND lg={l1} ELSE INSERT INTO [PM.AiJh]
                (
                    lg,
                    num,
                    isdel,
                    mId,
                    numBack
                )
                VALUES
                (   {l1},
                    -({num1 * _num}),
                    0,
                    '{mid}',
                    0
                    )");
            }
            if (l2 > 0 && num2 > 0)
            {
                sql.Add($@"IF EXISTS (SELECT * FROM [PM.AiJh] WHERE mId='{mid}' AND lg={l2})UPDATE [PM.AiJh] SET num=num-({num2 * _num}) WHERE mId='{mid}' AND lg={l2} ELSE INSERT INTO [PM.AiJh]
                (
                    lg,
                    num,
                    isdel,
                    mId,
                    numBack
                )
                VALUES
                (   {l2},
                    -({num2 * _num}),
                    0,
                    '{mid}',
                    0
                    )");
            }
            if (l3 > 0 && num3 > 0)
            {
                sql.Add($@"IF EXISTS (SELECT * FROM [PM.AiJh] WHERE mId='{mid}' AND lg={l3})UPDATE [PM.AiJh] SET num=num-({num3 * _num}) WHERE mId='{mid}' AND lg={l3} ELSE INSERT INTO [PM.AiJh]
                (
                    lg,
                    num,
                    isdel,
                    mId,
                    numBack
                )
                VALUES
                (   {l3},
                    -({num3 * _num}),
                    0,
                    '{mid}',
                    0
                    )");
            }
            if (sql.Any())
            {
                List<string> c = new List<string>();
                if (l1 > 0 && num1 > 0)
                {
                    c.Add($"{l1}*{num1}");
                }
                if (l2 > 0 && num2 > 0)
                {
                    c.Add($"{l2}*{num2}");
                }
                if (l3 > 0 && num3 > 0)
                {
                    c.Add($"{l3}*{num3}");
                }
                string cut = $"{_lg}={string.Join("+", c)}";
                sql.Add($"UPDATE [PM.AiSc] SET num=num-({_num}) WHERE mID='{mid}' AND lg={_lg}");
                sql.Add($"IF EXISTS (SELECT * FROM [PM.AiResult] WHERE mID = '{mid}' AND cutGroup = '{cut}') UPDATE [PM.AiResult] SET num = num + ({_num}),isUserAdd=1 WHERE mID = '{mid}' AND cutGroup = '{cut}' ELSE INSERT INTO [PM.AiResult] (cutGroup,num,mLength,twoCutNum,opType,mID,isAbandon,isUserAdd,numBack) VALUES ('{cut}',({_num}),{_lg},0,'ad','{mid}',0,1,({_num}))");
                if (nxsqlHelper.ExcuteSql(sql) > 0)
                {
                    Reload();
                    ShowMsg("添加成功！");
                }
            }
        }

        private void TextBox8_TextChanged(object sender, EventArgs e)
        {
            SumLength();
        }

        private void Button17_Click(object sender, EventArgs e)
        {
            if (comboBox2.SelectedValue == null)
            {
                ShowMsg("没有选择计划！");
                return;
            }
            this.SetControlEnableState(false);
            string mid = comboBox2.SelectedValue.ToString();
            double cutLenght = double.Parse(textBox1.Text);
            Task task = Task.Factory.StartNew(() =>
            {
                ai = new Ai(nxsqlHelper, mid, cutLenght, false);
            });
            task.ContinueWith(t =>
            {
                this.SetControlEnableState(true);
                Reload();
                ShowMsg("初始化完成！");
            }, TaskScheduler.FromCurrentSynchronizationContext());
        }

        private void ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (dataGridView3.SelectedRows.Count > 0)
            {
                string ID = dataGridView3.SelectedRows[0].Cells["ID"].Value.ToString();
                if (nxsqlHelper.GetCount("[PM.AiManufactureResult]", "resultId=" + ID) > 0)
                {
                    ShowError("该组合已有生产记录，请先删除生产记录！");
                    return;
                }
                string isUserAdd = dataGridView3.SelectedRows[0].Cells["人工添加"].Value.ToString();
                if (ai != null)
                {
                    ai.UserAddDel(comboBox2.SelectedValue.ToString(), ID);
                }
                if (nxsqlHelper.ExcuteSql("DELETE [PM.AiResult] WHERE ID=" + ID) > 0)
                {
                    Reload();
                    ShowMsg("移除成功！");
                }
            }
        }

        private readonly ChangeResult changeResult = new ChangeResult();

        private void ToolStripMenuItem2_Click(object sender, EventArgs e)
        {
            if (dataGridView3.SelectedRows.Count > 0)
            {
                string ID = dataGridView3.SelectedRows[0].Cells["ID"].Value.ToString();
                string isUserAdd = dataGridView3.SelectedRows[0].Cells["人工添加"].Value.ToString();
                string num = dataGridView3.SelectedRows[0].Cells["消耗支数"].Value.ToString();
                string group = dataGridView3.SelectedRows[0].Cells["锯切组合"].Value.ToString();

                if (isUserAdd == "否")
                {
                    SetShowFormDefault(changeResult);
                    changeResult.SetInfo(comboBox2.SelectedValue.ToString(), ID, num, group, this);
                    changeResult.ShowDialog();
                }
                else
                {
                    ShowError("只能转换自动结果！");
                }
            }
        }

        private void Button14_Click(object sender, EventArgs e)
        {
            string fileName = BaseDir + $@"\cutting_nogui.exe";
            if (!File.Exists(fileName))
            {
                if (!Directory.Exists(BaseDir))
                {
                    Directory.CreateDirectory(BaseDir);
                }
                if (!File.Exists(ZipFile))
                {
                    ShowError("找不到计算模块,请先配置计算模块！");
                    return;
                }
                ZipHelp.Compress(BaseDir, ZipFile, null);
            }
            string mid = null;
            if (comboBox2.SelectedValue != null)
            {
                mid = comboBox2.SelectedValue.ToString();
            }
            if (string.IsNullOrEmpty(mid))
            {
                ShowError("请选择要计算的计划！");
                return;
            }
            if (comboBox4.SelectedIndex == 0)
            {
                resultType = "1";
            }
            else
            {
                resultType = "2";
            }
            this.SetControlEnableState(false);
            Stopwatch sw = new Stopwatch();
            sw.Start();
            try
            {
                Process proc = new Process();
                proc.StartInfo.FileName = fileName;
                proc.StartInfo.UseShellExecute = true;
                proc.StartInfo.CreateNoWindow = true;
                proc.StartInfo.WorkingDirectory = Path.GetDirectoryName(fileName);
                proc.StartInfo.Arguments = mid + " " + resultType;
                proc.Start();
                proc.WaitForExit();
                GetResult(mid);
                Reload();
                scdt = nxsqlHelper.GetDataTableFromSql($"{scSql} WHERE mId='{comboBox2.SelectedValue}'");
                jhdt = nxsqlHelper.GetDataTableFromSql($"{jhSql} WHERE mId='{comboBox2.SelectedValue}'");
                dataGridView1.DataSource = scdt;
                dataGridView2.DataSource = jhdt;
                Sum(mid);
                sw.Stop();
                TimeSpan ts = sw.Elapsed;
                MessageBox.Show("计算成功，耗时:" + ts.Hours.ToString() + "小时" + ts.Minutes.ToString() + "分钟" + ts.Seconds + "秒" + ts.Milliseconds + "毫秒", "提示！");
            }
            catch (Exception ex)
            {
                ShowError(ex.Message);
            }
            this.SetControlEnableState(true);
        }

        private void GetResult(string mid)
        {
            List<string> up = new List<string>();
            nxsqlHelper.ExcuteSql($"UPDATE [PM.AiSc] SET num=numBack-ISNULL(realNum, 0) WHERE mID='{mid}';UPDATE [PM.AiJh] SET num=numBack-ISNULL(cutNum,0) WHERE mId='{mid}';UPDATE [PM.AiResult] SET isAbandon=0,abandonLg=0 WHERE mID='{mid}' AND abandonLg>=6 AND isAbandon=1");
            foreach (DataGridViewRow row in dataGridView3.Rows)
            {
                if (row.Cells["锯切组合"].Value != null && row.Cells["原料长度"].Value != null && row.Cells["消耗支数"].Value != null)
                {
                    string 锯切组合 = row.Cells["锯切组合"].Value.ToString().Trim();
                    string 原料长度 = row.Cells["原料长度"].Value.ToString().Trim();
                    string 消耗支数 = row.Cells["消耗支数"].Value.ToString().Trim();
                    if (消耗支数 != "0")
                    {
                        up.Add($"UPDATE [PM.AiSc] SET num=num-{消耗支数} WHERE mID='{mid}' AND lg={原料长度}");
                        string[] g = 锯切组合.Split('=')[1].Split('+');
                        foreach (var item in g)
                        {
                            string[] tmp = item.Split('*');
                            up.Add($"UPDATE [PM.AiJh] SET num=num-{消耗支数}*{tmp[1]} WHERE mId='{mid}' AND lg={tmp[0]}");
                        }
                        nxsqlHelper.ExcuteSql(up);
                        up.Clear();
                    }
                }
            }
            nxsqlHelper.ExcuteSql($"UPDATE [PM.AiResult] SET numBack=num WHERE mID='{mid}' AND (isUserAdd=0 OR isUserAdd IS NULL)");
        }

        private string resultType = "1";

        private void 配置计算模块ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DownFile downFile = new DownFile();
            SetShowFormDefault(downFile);
            downFile.ShowDialog();
        }

        private void ToolStripMenuItem3_Click(object sender, EventArgs e)
        {
            if (comboBox2.SelectedValue == null || dataGridView3.Rows.Count == 0)
            {
                ShowMsg("没有要保存的结果！");
                return;
            }
            string sheetName = comboBox2.Text.Replace('*', 'x').Split(')')[0].Split(')')[0].Replace('(', '_');
            SaveFileDialog saveFileDialog = new SaveFileDialog
            {
                Filter = "Excel|*.xlsx",
                FileName = sheetName + "锯切组合结果"
            };
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                DataTable dt = dataGridView3.DataSource as DataTable;
                try
                {
                    NopiHelp.ExportExcel(dt, saveFileDialog.FileName, sheetName + "锯切组合结果", comboBox2.Text + "锯切组合结果", false, "xlsx");
                    ShowMsg("导出成功！");
                }
                catch (Exception ex)
                {
                    ShowError("导出失败，请重试!" + ex.Message);
                }
            }
        }

        private void button18_Click(object sender, EventArgs e)
        {
            button2.Enabled = false;
            button18.Enabled = false;
            comboBox3.SelectedIndexChanged += ComboBox3_SelectedIndexChanged;
            Reload();
        }

        private void toolStripMenuItem4_Click(object sender, EventArgs e)
        {
            string mid = null;
            if (comboBox2.SelectedValue != null)
            {
                mid = comboBox2.SelectedValue.ToString();
            }
            if (string.IsNullOrEmpty(mid))
            {
                ShowError("请选择要计算的计划！");
                return;
            }
            GetResult(mid);
            scdt = nxsqlHelper.GetDataTableFromSql($"{scSql} WHERE mId='{comboBox2.SelectedValue}'");
            jhdt = nxsqlHelper.GetDataTableFromSql($"{jhSql} WHERE mId='{comboBox2.SelectedValue}'");
            dataGridView1.DataSource = scdt;
            dataGridView2.DataSource = jhdt;
            Sum(mid);
            ShowMsg("统计成功！");
        }

        private void comboBox5_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindCombox2();
        }

        private void textBox18_TextChanged(object sender, EventArgs e)
        {
            dt5.DefaultView.RowFilter = $"planSize LIKE '%{textBox18.Text.Trim()}%'";
        }

        private void textBox19_TextChanged(object sender, EventArgs e)
        {
            string str = textBox19.Text.Trim().Replace("*", "[*]");
            dt2.DefaultView.RowFilter = $"planstring LIKE '%{str}%'";
        }

        private void 清理缓存ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (Directory.Exists(BaseDir + "\\models"))
            {
                Directory.Delete(BaseDir + "\\models", true);
            }
            ShowMsg("缓存清理成功！");
        }

        private void button19_Click(object sender, EventArgs e)
        {
            string mid = null;
            if (comboBox2.SelectedValue != null)
            {
                mid = comboBox2.SelectedValue.ToString();
            }
            if (string.IsNullOrEmpty(mid))
            {
                ShowError("请选择要计算的计划！");
                return;
            }
            if (comboBox4.SelectedIndex == 0)
            {
                resultType = "1";
            }
            else
            {
                resultType = "2";
            }
            string fileName = BaseDir + $@"\cutting_nogui.exe";
            double cutLenght = double.Parse(textBox1.Text);
            if (!File.Exists(fileName))
            {
                if (!Directory.Exists(BaseDir))
                {
                    Directory.CreateDirectory(BaseDir);
                }
                if (!File.Exists(ZipFile))
                {
                    ShowError("找不到计算模块,请先配置计算模块！");
                    return;
                }
                ZipHelp.Compress(BaseDir, ZipFile, null);
            }
            nxsqlHelper.ExcuteSql($@"DELETE  [PM.AiResultBack_Sc] WHERE mID='{mid}' DELETE [PM.AiResultBack_Jh] WHERE mID='{mid}' DELETE [PM.AiResultBack] WHERE mID='{mid}'");
            Stopwatch sw = new Stopwatch();
            sw.Start();
            Process proc = new Process();
            proc.StartInfo.FileName = fileName;
            proc.StartInfo.UseShellExecute = true;
            proc.StartInfo.CreateNoWindow = true;
            proc.StartInfo.WorkingDirectory = Path.GetDirectoryName(fileName);
            proc.StartInfo.Arguments = mid + " " + resultType;
            SqlParameter[] sqlParameter = new SqlParameter[]
            {
                   sB_sqlHelper.CreatSqlParameter("mID", mid, SqlDbType.VarChar, ParameterDirection.Input),
                   sB_sqlHelper.CreatSqlParameter("rt", 0, SqlDbType.Int, ParameterDirection.Output)
            };
            double max1 = 0;
            double.TryParse(textBox21.Text, out max1);
            double min1 = 0;
            double.TryParse(textBox22.Text, out min1);
            double max2 = 0;
            double min2 = 0;
            for (double i = min1; i <= max1; i += 0.5)
            {
                double.TryParse(textBox23.Text, out max2);
                double.TryParse(textBox24.Text, out min2);
                if (min2 > 0 && min2 <= max2)
                {
                    for (double j = min2; j <= max2; j += 0.5)
                    {
                        if (i != j)
                        {
                            nxsqlHelper.ExcuteSql($"DELETE [PM.AiSc] WHERE mID='{mid}'");
                            ai = new Ai(nxsqlHelper, mid, cutLenght, false);
                            nxsqlHelper.ExcuteSql($"INSERT INTO [PM.AiSc] (lg,num,isdel,mID,numBack,realNum,cutHeadRate) VALUES ({i},0,0,'{mid}',0,0,0);INSERT INTO [PM.AiSc] (lg,num,isdel,mID,numBack,realNum,cutHeadRate) VALUES ({j},0,0,'{mid}',0,0,0)");
                            proc.Start();
                            proc.WaitForExit();
                            GetResult(mid);
                            nxsqlHelper.ExcuteProc("[C_PM.AiResultBack]", out var rt, sqlParameter);
                        }
                    }
                }
                else
                {
                    nxsqlHelper.ExcuteSql($"DELETE [PM.AiSc] WHERE mID='{mid}'");
                    ai = new Ai(nxsqlHelper, mid, cutLenght, false);
                    nxsqlHelper.ExcuteSql($"INSERT INTO [PM.AiSc] (lg,num,isdel,mID,numBack,realNum,cutHeadRate) VALUES ({i},0,0,'{mid}',0,0,0)");
                    proc.Start();
                    proc.WaitForExit();
                    GetResult(mid);
                    nxsqlHelper.ExcuteProc("[C_PM.AiResultBack]", out var rt, sqlParameter);
                }
            }
            sw.Stop();
            TimeSpan ts = sw.Elapsed;
            Reload();
            ShowMsg("计算完成！结果已保存到数据库中。");
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            Reload();
        }
    }
}